package com.cqu.hospitalsystem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqu.hospitalsystem.Vo.*;
import com.cqu.hospitalsystem.entity.Patient;
import com.cqu.hospitalsystem.entity.Prescription;
import com.cqu.hospitalsystem.service.PrescriptionService;
import com.cqu.hospitalsystem.utils.result.DataResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("prescription")
public class PrescriptionController {
    /**
     * 服务对象
     */
    @Resource
    private PrescriptionService prescriptionService;

    /**
     * 分页查询
     *
     * @param prescription 筛选条件
     * @param pageRequest  分页对象
     * @return 查询结果
     */
    @GetMapping
    @Operation(summary = "分页查询处方", description = "根据筛选条件和分页信息查询处方")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "400", description = "查询失败")
    })
    public ResponseEntity<Page<Prescription>> queryByPage(Prescription prescription, PageRequest pageRequest) {
        return ResponseEntity.ok(this.prescriptionService.queryByPage(prescription, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @Operation(summary = "根据ID查询处方", description = "根据处方ID查询单个处方")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "处方不存在")
    })
    public ResponseEntity<Prescription> queryById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(this.prescriptionService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param prescription 实体
     * @return 新增结果
     */
    @PostMapping
    @Operation(summary = "新增处方", description = "创建新的处方")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "201", description = "创建成功"),
            @ApiResponse(responseCode = "400", description = "创建失败")
    })
    public ResponseEntity<Prescription> add(Prescription prescription) {
        return ResponseEntity.ok(this.prescriptionService.insert(prescription));
    }

    /**
     * 编辑数据
     *
     * @param prescription 实体
     * @return 编辑结果
     */
    @PutMapping
    @Operation(summary = "编辑处方", description = "更新处方信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "400", description = "更新失败")
    })
    public ResponseEntity<Prescription> edit(Prescription prescription) {
        return ResponseEntity.ok(this.prescriptionService.update(prescription));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    @Operation(summary = "删除处方", description = "根据处方ID删除处方")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "400", description = "删除失败")
    })
    public ResponseEntity<Boolean> deleteById(Long id) {
        return ResponseEntity.ok(this.prescriptionService.deleteById(id));
    }

    /**
     * 显示已缴费处方单药品列表 ！！！
     *
     * @param patient
     * @return
     */
    @PostMapping("showPaidMedicine")
    @Operation(summary = "显示已缴费处方单药品列表", description = "根据患者信息显示已缴费处方单药品列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "无已缴费处方单")
    })
    public DataResult showPaidMedicine(@RequestBody Patient patient) {

        List<preMedicineVo> preMedicineVos = this.prescriptionService.showPaidMedicine(patient);
        for (preMedicineVo item : preMedicineVos) {
            //只把未退费的总价相加，3为已退费
            if (item.getState() != 3) {
                item.setTotalPrice(item.getPricePer() * item.getAmount());
            }
        }
        if (preMedicineVos.size() != 0) {
            return DataResult.successByDataArray(preMedicineVos);
        }
        //当天无预约，返回空
        return DataResult.successByData(null);

    }

    /**
     * 历史处方单药品列表
     *
     * @param prescription
     * @return
     */
    @PostMapping("showHistoryMedicine")
    @Operation(summary = "历史处方单药品列表", description = "根据处方ID显示历史处方单药品列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "无历史处方单")
    })
    public DataResult showHistoryMedicine(@RequestBody Prescription prescription) {
        System.out.println("这是历史药品列表");
        List<preMedicineVo> zww = this.prescriptionService.showHistoryMedicine(prescription.getPrescriptionId());
        Double totalPrice = 0.0;
        for (preMedicineVo item : zww) {
            //只把未退费的总价相加，3为已退费
            if (item.getState() != 3) {
                totalPrice = totalPrice + item.getPricePer() * item.getAmount();
                item.setTotalPrice(totalPrice);
            }
        }
        if (zww.size() != 0) {
            zww.get(0).setTotalPrice(totalPrice);
        }
        return DataResult.successByDataArray(zww);
    }

    /**
     * 未缴费处方单
     *
     * @param prescription
     * @return
     */
    @PostMapping("showUnpaidPre")
    @Operation(summary = "未缴费处方单", description = "根据处方ID显示未缴费处方单")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "无未缴费处方单")
    })
    public DataResult showUnpaidPre(@RequestBody Prescription prescription) {
        System.out.println("这是历史药品列表");
        List<preMedicineVo> zww = this.prescriptionService.showUnpaidPre(prescription.getPrescriptionId());
        Double totalPrice = 0.0;
        for (preMedicineVo item : zww) {
            totalPrice = totalPrice + item.getPricePer() * item.getAmount();
            item.setTotalPrice(totalPrice);
            System.out.println("这是未缴费的处方单列表");
            System.out.println(item);
        }
        if (zww.size() != 0) {
            zww.get(0).setTotalPrice(totalPrice);
        }
        return DataResult.successByDataArray(zww);
    }

    /**
     * 交处方单费用
     *
     * @param prescription
     * @return
     */
    @PostMapping("payMedicine")
    @Operation(summary = "交处方单费用", description = "根据处方ID交处方单费用")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "支付成功"),
            @ApiResponse(responseCode = "400", description = "支付失败")
    })
    public DataResult payMedicine(@RequestBody Prescription prescription) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("isSuccess", this.prescriptionService.payMedicine(prescription.getPrescriptionId()));
        return DataResult.successByData(jsonObject);
    }


    /**
     * 查看处方单
     *
     * @param prescription
     * @return
     */
    @PostMapping("showMedicine")
    @Operation(summary = "查看处方单", description = "根据处方ID查看处方单")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "处方单不存在")
    })
    public DataResult showMedicine(@RequestBody Prescription prescription) {
        System.out.println("查看处方单");
        System.out.println(prescription.getPrescriptionId());
        prescriptionVo prescription1 = this.prescriptionService.showMedicine(prescription.getPrescriptionId());
        System.out.println(prescription1);
        return DataResult.successByData(this.prescriptionService.showMedicine(prescription.getPrescriptionId()));
    }

    @PostMapping("savePrescription")
    @Operation(summary = "保存处方", description = "根据处方信息保存处方")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "保存成功"),
            @ApiResponse(responseCode = "400", description = "保存失败")
    })
    public DataResult savePrescription(@RequestBody MediPresNew mediPresNew) throws ParseException {
        List<MedicineDetail> MAlist = mediPresNew.getMedicineList();
        Long regId = mediPresNew.getRegId();

        List<Long> medicineList = new LinkedList<>();
        List<Integer> amountList = new LinkedList<>();

        for (MedicineDetail m : MAlist) {
            if (m.getAmount() == 0) continue;
            medicineList.add(m.getMedicineId());
            amountList.add(m.getAmount());
        }

        MediPres medipres = new MediPres();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        medipres.setPrescriptionTime(sdf.format(new Date()));
        medipres.setMedicineList(medicineList);
        medipres.setRegId(regId);
        medipres.setAmountList(amountList);

        System.out.println("savePrescription");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("isSuccess", this.prescriptionService.savePrescription(medipres));
        System.out.println(jsonObject);
        return DataResult.successByData(jsonObject);
    }

}

